package com.aier.controller.invoice;

import com.aier.bean.common.CommonResult;
import com.aier.bean.common.GlobalCode;
import com.aier.bean.invoice.HengdaInvoice;
import com.aier.exception.CastException;
import com.aier.service.invoice.HengdaInvoiceService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 恒达货代发票controller
 */
@Controller
@CrossOrigin
@RequestMapping("/hengda_invoice")
public class HengdaInvoiceController {

    @Autowired
    private HengdaInvoiceService hengdaInvoiceService;

    @RequestMapping("/get_by_staff_id")
    @ResponseBody
    public CommonResult getHengdaInvoiceByStaffId(@RequestBody Map<String,String> map){
        List<HengdaInvoice> foreignBaseList = hengdaInvoiceService.getHengdaInvoiceByStaffId(map.get("staffId"));
        return CommonResult.success(foreignBaseList);
    }

    @RequestMapping("/modify_or_insert")
    @ResponseBody
    public CommonResult modifyOrInsertHengdaInvoice(@RequestBody HengdaInvoice hengdaInvoice){
        hengdaInvoiceService.modifyOrInsertHengdaInvoice(hengdaInvoice);
        return CommonResult.success();
    }


    @RequestMapping("/remove_by_fba")
    @ResponseBody
    public CommonResult removeInsertHengdaInvoice(@RequestBody Map<String,String> map){
        hengdaInvoiceService.removeHengdaInvoice(map.get("fbaCode"));
        return CommonResult.success();
    }

    @GetMapping("/download_template")
    public void downloadTemplate(HttpServletResponse response,@RequestParam(value = "staffId") String staffId) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("恒达货代发票信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 创建空数据列表
        List<HengdaInvoice> hengdaInvoiceList = hengdaInvoiceService.getHengdaInvoiceByStaffId(staffId);

        // 3. 使用EasyExcel写入模板
        EasyExcel.write(response.getOutputStream(), HengdaInvoice.class)
                .sheet("基础数据")
                .doWrite(hengdaInvoiceList);
    }


    @RequestMapping("/batch_upload")
    @ResponseBody
    @Transactional
    public CommonResult batchUploadForeignBase(@RequestParam("file") MultipartFile file){
        try {
            List<HengdaInvoice> hengdaInvoiceList = EasyExcel.read(file.getInputStream())
                    .head(HengdaInvoice.class)
                    .sheet()
                    .doReadSync();
            // 处理数据
            hengdaInvoiceList.forEach(hengdaInvoice->processForeignBase(hengdaInvoice));
            return CommonResult.success();
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.error(GlobalCode.READ_FAIL);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(GlobalCode.EXPORT_FAIL);
        }
    }

    @RequestMapping("/generate_invoice")
    @CrossOrigin
    public void generateInvoice(HttpServletRequest request,HttpServletResponse response, @RequestBody List<HengdaInvoice> hengdaInvoiceList) throws IOException {
        hengdaInvoiceService.batchExportCargoOrderTmpZip(request,response,hengdaInvoiceList);
    }


    private void processForeignBase(HengdaInvoice hengdaInvoice) {
        // 这里实现业务逻辑，例如：
        // 1. 数据校验
        if (hengdaInvoice.getFbaCode() == null || hengdaInvoice.getFbaCode().isEmpty()) {
            CastException.cast(GlobalCode.FBA_IS_EMPTY);
        }


        // 2. 保存/修改数据库数据
        hengdaInvoiceService.modifyOrInsertHengdaInvoice(hengdaInvoice);
    }

}
